<?php

use Yaf\Controller_Abstract;

/**
 * Class BaseController
 */
class BaseController extends Controller_Abstract
{
    /**
     * JSON响应
     *
     * @param array $data
     * @param int $ret
     * @param string $msg
     * @return bool
     */
    protected function json(array $data = [], int $ret = 200, string $msg = ''):bool
    {
        $rs = [
            'ret'   =>  $ret,
            'data'  =>  is_array($data) && empty($data) ? (object)$data : $data,
            'msg'   =>  $msg
        ];
        $response = $this->getResponse();
        $response->setHeader('Content-Type', 'application/json; charset=utf-8');
        $response->setBody(json_encode($rs, JSON_UNESCAPED_UNICODE));
        return false;
    }

    /**
     * 添加允许跨域的报文头
     */
    protected function Cors()
    {
        $response = $this->getResponse();
        $response->setHeader( 'access-control-allow-origin', '*' );
        $response->setHeader( 'access-control-allow-credentials', 'true' );
        $response->setHeader( 'access-control-allow-headers', 'Content-Type' );
        $response->setHeader( 'access-control-allow-methods', 'GET, POST' );
    }
}
